<?php
// 开启所有错误报告
error_reporting(E_ALL);
// 显示错误信息
ini_set('display_errors', 1);

session_start();
require 'db_connect.php'; // 数据库连接文件,$conn是数据库对象

// 检查登录是否正常-----------------------------------------------------------------------------------------------------
// 检查登录状态和角色
if (!isset($_SESSION['isLoggedIn']) || !$_SESSION['isLoggedIn'] || $_SESSION['role'] !== 'student') {
    header('Location: login.php');//重定向到登录页面
    exit;
}

// 获取并检查学生ID
$studentID = isset($_SESSION['userId']) ? intval($_SESSION['userId']) : null;
if ($studentID === null) {
    header('Location: login.php');
    exit;
}
//-----------------------------------------------------------------------------------------------------------------

$activeSection = $_GET['section'] ?? 'profile';//检查活跃页面，没有默认个人信息页

try {
    // 获取学生基本信息
    $stmt = $conn->prepare("
        SELECT s.*, d.DepartmentName 
        FROM Student s
        JOIN Department d ON s.DepartmentID = d.DepartmentID
        WHERE s.StudentID = ?
    ");
    $stmt->bind_param("i", $studentID);//把登录信息拿到的studentID传到问号那里
    $stmt->execute();//执行查询
    $studentInfo = $stmt->get_result()->fetch_assoc();//拿到结果，包括姓名，性别，学号，学院ID，入学日期
    
    if (!$studentInfo) {
        die("找不到该学生的信息");
    }
    
    $departmentName = $studentInfo['DepartmentName'];

    // 获取已选课程
    if ($activeSection == 'enrolled') {
        $stmt = $conn->prepare("
             SELECT o.OfferingID, c.CourseName, c.Credit, t.Name AS TeacherName, e.Grade
        FROM Enrollment e
        JOIN CourseOffering o ON e.OfferingID = o.OfferingID
        JOIN Course c ON o.CourseID = c.CourseID
        JOIN Teacher t ON o.TeacherID = t.TeacherID
        WHERE e.StudentID = ?
        ");
        $stmt->bind_param("i", $studentID);
        $stmt->execute();
        $enrolledCourses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    // 获取可选课程（当前学期）
    if ($activeSection == 'available') {
        $currentYear = date('Y');
        $currentSemester = (date('n') < 7) ? 'spring' : 'autumn';

        $stmt = $conn->prepare("
            SELECT o.OfferingID, c.CourseName, c.Credit, t.Name AS TeacherName
            FROM CourseOffering o
            JOIN Course c ON o.CourseID = c.CourseID
            JOIN Teacher t ON o.TeacherID = t.TeacherID
            LEFT JOIN Enrollment e ON o.OfferingID = e.OfferingID AND e.StudentID = ?
            WHERE o.Year = ? 
                AND o.Semester = ?
                AND (c.DepartmentID = ? OR c.DepartmentID IS NULL)
                AND e.OfferingID IS NULL
        ");
        $stmt->bind_param("iiss", 
            $studentID,
            $currentYear,
            $currentSemester,
            $studentInfo['DepartmentID']
        );
        $stmt->execute();
        $availableCourses = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    $stmt = $conn->prepare("
        SELECT SUM(c.Credit) AS TotalCredits
        FROM Enrollment e
        JOIN CourseOffering o ON e.OfferingID = o.OfferingID
        JOIN Course c ON o.CourseID = c.CourseID
        WHERE e.StudentID = ? AND e.Grade >= 60
    ");
    $stmt->bind_param("i", $studentID);
    $stmt->execute();
    $creditResult = $stmt->get_result()->fetch_assoc();
    $totalCredits = $creditResult['TotalCredits'] ?? 0; // 处理 NULL 值

    // 将学分数据传递到前端
    $studentInfo['TotalCredits'] = $totalCredits;

} catch (Exception $e) {
    die("数据库错误: " . $e->getMessage());
}

include 'student_view.php'; // 包含前端页面